;; -*- Emacs-Lisp -*-

;; Time-stamp: <2010-04-14 15:45:40 Wednesday by ahei>

(unless is-before-emacs-21
  (eal-define-keys-commonly
   global-map
   `(("C-x F" find-grep)
     ("C-x f" find-grep-in-dir)
     ("C-x M-F" find-grep-current-word)))
  
  (eal-define-keys
   'grep-mode-map
   `(("q" bury-buffer)
     ("Q" kill-this-buffer)
     ("<" beginning-of-buffer)
     (">" end-of-buffer)
     ("u" scroll-down)
     ("/" describe-symbol-at-point)
     ("t" sb-toggle-keep-buffer)
     ("N" select-buffer-forward)
     ("P" select-buffer-backward)
     ("L" count-brf-lines))))

(autoload 'grep-apply-setting "grep"
  "Set SYMBOL to VALUE, and update `grep-host-defaults-alist'.
SYMBOL should be one of `grep-command', `grep-template',
`grep-use-null-device', `grep-find-command',
`grep-find-template', `grep-find-use-xargs', or
`grep-highlight-matches'.")

;;;###autoload
(defun find-grep-in-dir (dir)
  "Run `find-grep' in directory DIR."
  (interactive (list (read-directory-name "Directory to find in: " default-directory "" t)))
  (let ((prompt (concat "find " dir " -type f ! -wholename \"*/.svn*\" ! -wholename \"*~\" -print0 | xargs -0 -e grep -nH -e ")))
    (if is-after-emacs-23
        (grep-apply-setting 'grep-find-command prompt)
      (setq grep-find-command prompt))
    (call-interactively 'find-grep)))

;;;###autoload
(defun grep-current-word (dir &optional is-prompt)
  "Run `grep' to find current word in directory DIR."
  (interactive
   (list
    (read-directory-name "Directory to grep in: " default-directory "" t)
    current-prefix-arg))
  (let* ((word (grep-tag-default))
         (commands (concat grep-command word " " dir "/*")))
    (if is-prompt
        (grep (read-shell-command "Run grep (like this): " commands 'grep-history))
      (grep commands))))

;;;###autoload
(defun grep-current-word-in-current-dir (&optional is-prompt)
  "Run `grep' to find current word in directory DIR."
  (interactive "P")
  (grep-current-word default-directory is-prompt))

;;;###autoload
(defun grep-settings ()
  "settings for `grep'."
  (defvar grep-find-prompt
    "find . -type f ! -wholename \"*/.svn*\" ! -wholename \"*~\" -print0 | xargs -0 -e grep -nH -e "
    "*Default prompt of `grep-find'.")

  (if is-after-emacs-23
      (grep-apply-setting 'grep-find-command grep-find-prompt)
    (setq grep-find-command grep-find-prompt))

  (defvar grep-ignore-case nil "When run `grep' ignore case or not.")

  (when grep-ignore-case
    (if is-after-emacs-23
        (grep-apply-setting 'grep-command "grep -inH -e ")
      (setq grep-command "grep -inH -e "))))

(eval-after-load "grep"
  `(grep-settings))

(provide 'grep-settings)
